<style lang="stylus">
bottom-img($img, $w, $h)
  &::before
    content ''
    display block
    width $w
    height $h
    background url('../assets/detail/' + $img + '.png') no-repeat center
    background-size cover
    margin 0 auto 10px
.film-detail
  min-height 100%
  overflow hidden
  // padding-bottom 100px
  .douban
    width 100px
    line-height 40px
    background-color #ffc164
    border-radius 6px
    min-width 130px
  .right-arrow
    background url("../assets/detail/right_arrow_black.png") no-repeat right center
    background-size 13px 21px
  .set-desc
    color #767676
    align-self flex-end
    padding-bottom 1px
  .movie-sets
    overflow-x scroll
    flex-wrap nowrap
  .movie-set
    min-width 120px
    line-height 120px
    background-color #f8f8f8
    border-radius 6px
    color #494949
    & + .movie-set
      margin-left 12px
    &.active
      background-color #4d3ebc
      color #fff
    &.page-set
      width calc((100% - 4 * 28px) / 5)
      height @width
    &.page-set:not(:nth-child(5n+1))
      margin-left 28px
    &.page-set:nth-child(5n+1)
      margin-left 0
  .bottom-menu
    position fixed
    bottom 0
    width 100%
    height 110px
    color #595959
    z-index 4
    max-width 750px;/*no*/
    margin 0 auto
  .favor
    bottom-img(icon_favor, 48px, 48px)
    &.favored
      bottom-img(icon_favored, 48px, 48px)
  .cache
    bottom-img(icon_cache, 48px, 48px)
  .share
    bottom-img(icon_share, 34px, 35px)
  .detail-close
    width 32px
    height 32px
    background url("../assets/detail/icon_close_black.png") no-repeat
    background-size cover
  .mgt-70
    margin-top 70px
  .page-nums
    overflow-x scroll
    flex-wrap nowrap
    & > div
      min-width 200px
      &.two
        min-width 120px
      &.three
        min-width 160px
  .page-num
    padding-bottom 5px
    display inline-block
    border-bottom 4px solid transparent
    &.active
      border-bottom 6px solid #4d3ebc
  .player
    height 460px
    background-color rgba(0, 0, 0, 0.9)
    margin-bottom 20px
    justify-content center
    position relative
    .player-back
      position absolute
      top 10px
      left 10px
      width 86px
      height 30px
      line-height 30px
      background url("../assets/search/icon_back.png") no-repeat 5px center
      background-size 12px
      color #fff
      font-size 30px
      padding-left 20px
      z-index 2
  .hint-1, .hint-2
    color #9b9b9b
  .download
    width 450px
    height 93px
    transform scale(0.7, 0.7)
    background url("../assets/icon_download.png")
    background-size cover
  .intro-top
    position fixed
    top 0
    left 0
    width 100%
    background-color #fff
</style>

<template lang="pug">
.film-detail.pdb-30
  div(v-show="!showIntro && !showSets")
    .player.flex.column(v-if="!isApp")
      .player-back(@click="onGoHome") 返回
      .hint-1.fz-20 您正在观看热门影片
      .hint-2.fz-20.mgt-10 下载APP后即可观看
      .download.mgt-10(@click="onDownload")
    .flex.pdh-20.pdt-30
      .bold {{movie.title}}
      .flex-1
      .fz-26.right-arrow.pdr-20(@click="onToggleIntro") 简介
    .fz-24.mgt-22.line-clamp-3.pdh-20
      strong 简介：
      span.gray-99.mgl-16 {{movie.intro}}
    .flex.mgt-32.pdb-24.bdb
      .douban.fz-24.white.center.mgl-22(v-if="movie.score > 0") 评分 {{formatScore(movie.score)}}
      .mgl-22.fz-22.gray-99.mgr-30 {{movieCategory() + " • "}}全{{movie.totalNum}}集 • 播放{{playCount}}
    .mgt-22.flex.pdh-20(v-if="movie.updateNum > 1")
      .fz-28.bold 选集
      .flex-1.fz-22.mgl-22.set-desc {{movie.updateDesc}}
      .fz-26.right-arrow.pdr-20(@click="onToggleSets") 全部
    .mgt-42.flex.pdh-20.movie-sets(v-if="movie.updateNum > 1")
      .movie-set.center(v-for="(set, index) in sets(movie.updateNum)", :key="index", :class="{active: selectedSet - 1 === index}", @click="selectSet(index)") {{index + 1}}
    .flex.pdh-20.mgt-50.pdb-30(v-if="recommends.length")
      .fz-28.bold 猜你喜欢
      .flex-1
      .fz-26.right-arrow.pdr-20(@click="onGoHome") 全部
    search-item.pdh-20(v-for="(recommend, index) in recommends", :key="index", :item="recommend")
    //- .flex.bottom-menu.bdt.bg-white.fz-26(v-if="!config.env.isApp")
    //-   .flex-1.center.favor(@click="onFavor", :class="{favored: !!favorId}") 收藏
    //-   .flex-1.center.cache(@click="onCache") 缓存
    //-   .flex-1.center.share(@click="onShare") 分享
  div.pdt-50(v-show="showIntro")
    .flex.pdl-20.pdr-44.bdb.pdb-18.pdt-30.intro-top
      .bold.flex-1 影片简介
      .detail-close(@click="onToggleIntro")
    .pdl-20.pdt-36.mgt-36
      .bold 影片名称：{{movie.title}}
      .mgt-34.fz-24 类型：{{movieCategory('/')}}
      .mgt-34.fz-24 导演：{{movie.director}}
      .mgt-34.fz-24 演员：{{movie.actor}}
      .mgt-34.fz-24 播放：{{movie.countPlay}}次
      .flex.mgt-26(v-if="movie.score > 0")
        .fz-24 评分：
        .douban.fz-24.white.center 评分: {{formatScore(movie.score)}}
      .mgt-70.bold 简介
      .gray-99.mgt-44.fz-26 {{movie.intro}}
  div(v-show="showSets")
    .flex.pdt-30.pdl-28.pdb-16.bdb.pdr-18
      .bold.fz-36 选集
      .flex-1.fz-22.mgl-50.set-desc {{movie.updateDesc}}
      .detail-close(@click="onToggleSets")
    .flex.pdl-26.page-nums
        .fz-30.bold.pdt-24.flex-1(v-for="(p, index) in pageNums", :key="index", @click="onChangePageNum(index)",
          :class="{'two': index === 0, 'three': index < 19 && index > 0}")
            span.page-num(:class="{'active': currentPageNum === index}") {{p}}
    .flex.pdh-20.flex-wrap
      .movie-set.page-set.mgt-24.center(v-for="(set, index) in pageSets[currentPageNum]", :key="index", :class="{active: selectedSet - 1 === index}", @click="selectSet(index)") {{(PAGE_COUNT * currentPageNum) + index + 1}}
</template>

<script>
import SearchItem from '../components/SearchItem.vue'
import { CACHE_KEY } from '../const'

const PAGE_COUNT = 50
export default {
  name: 'film-detail',
  components: { SearchItem },
  data() {
    return {
      movie: {
        movieId: 0,
        channel: {}
      },
      selectedSet: 1,
      recommends: [],
      showIntro: false,
      showSets: false,
      currentPageNum: 0,
      PAGE_COUNT,
      movieSetDom: null,
      favorId: 0,
      isApp: false
    }
  },

  watch: {
    '$route.params.id': function () {
      this.loadPageData()
    }
  },

  mounted() {
    this.isApp = this.config.env.isApp
    this.loadPageData()
  },

  computed: {
    favorParams() {
      return { movieId: this.movie.movieId, userId: this.user.userId }
    },

    pageSets() {
      const sets = []
      const pageNum = Math.floor(this.movie.updateNum / PAGE_COUNT)
      for (let i = 0; i < pageNum; i++) {
        sets.push(new Array(PAGE_COUNT).fill(0))
      }

      const lastPageCount = this.movie.updateNum - (pageNum * PAGE_COUNT)
      if (lastPageCount) {
        sets.push(new Array(lastPageCount).fill(0))
      }
      return sets
    },

    pageNums() {
      const nums = []
      const sets = this.pageSets
      for (let i = 0; i < sets.length; i++) {
        const pageNum = sets[i].length
        if (pageNum === 1) {
          nums.push(((PAGE_COUNT * i) + 1))
        } else {
          nums.push(`${(PAGE_COUNT * i) + 1}-${(PAGE_COUNT * i) + pageNum}`)
        }
      }
      return nums
    },

    playCount() {
      const { countPlay = 0 } = this.movie
      if (countPlay < 10000) {
        return `${countPlay}次`
      }
      return `${(countPlay / 10000).toFixed(2)}万次`
    }
  },

  methods: {
    onDownload() {
      location.href = 'http://ptys.baiduux.com/h5/xiaopishare.html'
    },

    onGoHome() {
      if (this.config.env.isBrowser) {
        this.onLinkPage('/home')
      } else {
        this.action('home')
      }
    },

    onToggleIntro() {
      this.showIntro = !this.showIntro
    },

    onToggleSets() {
      this.showSets = !this.showSets
    },

    onChangePageNum(pageNum) {
      this.currentPageNum = pageNum
    },

    sets(num) {
      return new Array(num).fill(0)
    },

    selectSet(set) {
      if (this.selectedSet == (this.currentPageNum * PAGE_COUNT) + set + 1) {
        return;
      }
      this.selectedSet = (this.currentPageNum * PAGE_COUNT) + set + 1
      this.onItemDispatch(this.movie, this.selectedSet)

      // 动态调整剧集的位置
      if (!this.movieSetDom) {
        this.movieSetDom = this.$el.querySelector('.movie-sets')
      }
      // let count = Math.floor(document.body.clientWidth / this.movieSetDom.children[0].clientWidth)
      
      // if (this.selectedSet <= 4) {
      //   this.movieSetDom.scrollTo(0, 0)
      // } else {
      //   // console.log((this.selectedSet - count / 2 - 0.5) * this.movieSetDom.children[0].clientWidth)
      //   this.movieSetDom.scrollTo((this.selectedSet - count / 2 - 0.5) * (this.movieSetDom.children[0].clientWidth + document.body.clientWidth / 8 * .12), 0)
      // }
    },

    movieCategory(separator = ' • ') {
      const categories = []
      if (this.movie.area) {
        categories.push(this.movie.area.value)
      }

      if (this.movie.category) {
        categories.push(this.movie.category.value)
      }

      if (this.movie.channel) {
        categories.push(this.movie.channel.value)
      }
      return categories.join(separator)
    },

    onCache() {
      if (this.config.env.isApp) {
        this.action('filmCache', {
          id: this.$route.params.id,
          userId: this.user.userId,
          set: this.selectedSet,
          movieTitle: this.movie.name,
          videoTotalCount: this.movie.totalNum
        })
      } else {
        this.$toast('点击了缓存')
      }
    },

    onShare() {
      if (this.config.env.isApp) {
        let desc = this.movie.intro
        if (desc.length > 50) {
          desc = `${desc.substring(0, 50)}...`
        }

        this.action('share', {
          title: this.movie.title,
          url: location.href,
          desc,
          icon: this.movie.cover
        })
      } else {
        this.$toast('点击了分享')
      }
    },

    onFavor() {
      if (!this.user.userId) {
        if (this.config.env.isApp) {
          this.action('login')
        } else {
          this.$router.push('/login')
        }
        return
      }

      if (!this.favorId) {
        this.$get('user/collect/add', this.favorParams).then(favorId => {
          this.favorId = favorId
          this.$toast('影片收藏成功，可在\'我的-收藏\'查看')
        })
      } else {
        this.$get('user/collect/delete', { ids: this.favorId }).then(() => {
          this.favorId = ''
          this.$toast('已取消收藏')
        })
      }
    },

    loadPageData() {
      this.movie.movieId = this.$route.params.id

      // 记录历史
      const movieIds = this.getStore(CACHE_KEY.BROWSER_HISTORY) || []
      if (movieIds.indexOf(+this.movie.movieId) === -1) {
        movieIds.push(+this.movie.movieId)
        this.saveStore(CACHE_KEY.BROWSER_HISTORY, movieIds)
      }

      this.$get('movie/detail', { movieId: this.movie.movieId }).then(movie => {
        this.movie = movie
      })

      // 推荐列表
      this.$get('movie/recommend', { movieId: this.movie.movieId, num: 20, userId: this.userId }).then(recommends => {
        if (recommends.length && this.config.env.isApp) {
          this.action('getKeywordAdv', this.movie.name).then(res => {
            if (res) {
              recommends.splice(1, 0, res)
            }
          })
        }
        this.recommends = recommends
      })

      if (this.user.userId) {
        this.$get('user/collect/check', this.favorParams).then(favorId => {
          this.favorId = favorId
        })
      }
    },

    onBack() {
      window.history.go(-1)
    }
  }
}
</script>
